package com.haochu.novel.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.testnovel.R;
import com.haochu.novel.db.DBHelper;
import com.haochu.novel.util.Constants;
import com.haochu.novel.util.MeasureUtil;
import com.haochu.novel.util.SpeekUitl;
import com.haochu.novel.vo.Book;

/**
 * @author fuhuichao
 * 2017年6月20日17:13:40
 * 小说内容
 */
@SuppressLint("ClickableViewAccessibility")
public class BookContentActivity extends Activity implements OnTouchListener, OnClickListener {

	// 自定义view
	BookContentView mBookContentView;
	// 文字工具工厂
	private BookFactory bookFactory;
	// 文字当前页的位图
	private Bitmap mCurPageBitmap, mNextPageBitmap;
	// 页面背景图片
	private Bitmap backGroundBitmap;
	// 文字当前页的canvas
	private Canvas mCurCanvas, mNextCanvas;
	// 屏幕尺寸
	int screenWidth, screenHeight;
	// 点击自定义view时的坐标
	float touchX, touchY, touchOldX, touchOldY;
	// 点击时Y轴方向上的有效区域
	float partUpY, partDownY;
	// 参数存储类
	private SharedPreferences preference;
	private SharedPreferences.Editor editor;
	// 菜单栏
	private PopupWindow menuPopup;
	// 弹出菜单栏
	private View menuPopupView;
	private Button btnFontSizeBigger, btnFontSizeSmaller, btnCategory, btnTTS;
	private ImageView btn_back, btn_search, btn_bookmark;
	private RelativeLayout pop_toolbar;
	private LinearLayout pop_menubar;
	// 数据库工具
	private DBHelper dbHelper;
	// 小说
	private Book currentBook;
	// 语音合成工具
	private SpeekUitl speekUtil;
	// 吐司
	private Toast mToast;
	// 标记播放或者暂停
	private boolean isSpeaking;
	// 播放按钮图标
	private Drawable drawablePlay;
	// 暂停按钮图标
	private Drawable drawablePause;
	
	@SuppressLint("ShowToast") 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//设置无标题  
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        //设置全屏  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
        
        setContentView(R.layout.layout_book_content);
        
		// 监听触摸操作
        mBookContentView = (BookContentView) findViewById(R.id.mBookContentView);
		mBookContentView.setOnTouchListener(this);
		
		// 初始化吐司
		mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		
		// 初始化popup
		initPopup();
		
		// 获取屏幕尺寸
		screenWidth = MeasureUtil.getScreenWidth(this);
		screenHeight = MeasureUtil.getScreenHeight(this);
		
		// 计算Y轴方向有效区域（上下浮动十分之二）
		partUpY = screenHeight / 2 * 0.8f;
		partDownY = screenHeight / 2 * 1.2f;
		
		// 获取页面背景图片
		backGroundBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.book_content_bg);
		backGroundBitmap = Bitmap.createScaledBitmap(backGroundBitmap, screenWidth, screenHeight, true);
		
		// 创建位图，初始化canvas
		mCurPageBitmap = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
		mNextPageBitmap = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
		mCurCanvas = new Canvas(mCurPageBitmap);
		mNextCanvas = new Canvas(mNextPageBitmap);
		
		// 将位图传递给自定义view
		mBookContentView.setmCurPageBitmap(mCurPageBitmap, mNextPageBitmap);

        // 创建数据库工具
        dbHelper = DBHelper.getInstance(this);
        int bookId = getIntent().getIntExtra("bookId", 0);
		
		// 开始启动工厂
		preference = getSharedPreferences(Constants.REFERENCE_FILENAME, MODE_PRIVATE);
		bookFactory = new BookFactory(this, preference, bookId);

		// 加载后就开始智能断章和分页
		getCategories();
		
		// 传递页面背景图片
		bookFactory.setBackGroundBitmap(backGroundBitmap);
		
		// 画一页内容
		bookFactory.pageNext();
		bookFactory.doDraw(mCurCanvas);
		
		// 初始语音工具
		drawablePlay = getResources().getDrawable(R.drawable.play);
		drawablePause = getResources().getDrawable(R.drawable.pause);
		speekUtil = new SpeekUitl(BookContentActivity.this, bookFactory);
		isSpeaking = false;
		changeBtnDrawableTTS();
	}
	
	
	/**
	 * 初始化popup
	 */
	@SuppressLint("InflateParams") 
	public void initPopup(){
		menuPopupView = getLayoutInflater().inflate(R.layout.layout_pop_menu, null);
		menuPopupView.setOnTouchListener(this);
		menuPopup = new PopupWindow(menuPopupView, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
		menuPopup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
		
		// 初始化弹出菜单按钮
		pop_toolbar = (RelativeLayout) menuPopupView.findViewById(R.id.pop_toolbar);
		pop_menubar = (LinearLayout) menuPopupView.findViewById(R.id.pop_menubar);
		btn_back = (ImageView) menuPopupView.findViewById(R.id.btn_back);
		btn_search = (ImageView) menuPopupView.findViewById(R.id.btn_search);
		btn_bookmark = (ImageView) menuPopupView.findViewById(R.id.btn_bookmark);
		btnFontSizeBigger = (Button) menuPopupView.findViewById(R.id.btnFontSizeBigger);
		btnFontSizeSmaller = (Button) menuPopupView.findViewById(R.id.btnFontSizeSmaller);
		btnCategory = (Button) menuPopupView.findViewById(R.id.btnCategory);
		btnTTS = (Button) menuPopupView.findViewById(R.id.btnTTS);
		
		// 设置按钮click监听
		btn_back.setOnClickListener(this);
		btn_search.setOnClickListener(this);
		btn_bookmark.setOnClickListener(this);
		btnFontSizeBigger.setOnClickListener(this);
		btnFontSizeSmaller.setOnClickListener(this);
		btnCategory.setOnClickListener(this);
		btnTTS.setOnClickListener(this);
	}
	
	/**
	 * 加载后就获取一次目录
	 */
	public void getCategories(){
		
		// 开始智能断章 
		new Thread(new Runnable() {
			@Override
			public void run() {
				bookFactory.startAnalyzeCategories();
			}
		}).start();

//		// 开始计算分页
//		new Thread(new Runnable() {
//			@Override
//			public void run() {
//				bookFactory.startPagination();
//				
//				// 发消息刷新页面
//				refreshCurPage();
//			}
//		}).start();
		
		// 刷新智能断章的进度
		new Thread(new Runnable() {
			@Override
			public void run() {
            	float percent = 0f;
            	Message m = null;
            	Bundle b = null;
            	while(percent < 100){
            		// 获取进度百分比
            		percent = bookFactory.getCategoryPercent();

            		// 发送消息
            		b = new Bundle();
            		b.putFloat("p", percent);
            		m = new Message();
            		m.setData(b);
            		m.what = 1;
            		mHandler.sendMessage(m);
            		
            		// 每次刷新间隔0.5秒
            		try {
            			Thread.sleep(500);
            		} catch (InterruptedException e) {
            			e.printStackTrace();
            		}
            	}
			}
		}).start();
	}
	
	/**
	 * 	自定义view的touch监听
	 */
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		touchX = event.getX();
		touchY = event.getY();

		if(v == menuPopupView){
			if(event.getAction() == MotionEvent.ACTION_UP){
				Log.d("iiii", pop_toolbar.getBottom() + "--" + pop_menubar.getTop());
				// 若点击在弹出菜单外面，则关闭弹出
				if(touchY > pop_toolbar.getBottom() && touchY < pop_menubar.getTop()){
					dismissMenuPop();
				}
			}
		}
		if(v == mBookContentView){
			switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					touchOldX = touchX;
					touchOldY = touchY;
					break;
				case MotionEvent.ACTION_UP:
					if(touchX > touchOldX){
						// 往右滑

					}else if(touchX < touchOldX){
						// 往左滑
						
					}else if(touchY < partUpY){
						// 点击上区域
						if(bookFactory.isPageFirst()){
							showTip(R.string.first_page);
						}else{
							doPagePre();
						}
					}else if(touchY > partDownY){
						// 点击下区域
						if(bookFactory.isPageLast()){
							showTip(R.string.last_page);
						}else{
							doPageNext();
						}
					}else{
						// 点击中间区域， 弹出菜单，并加载动画
						menuPopup.showAtLocation(mBookContentView, Gravity.BOTTOM, 0, 0);
//						AnimationUtil.showMenuBarAnimate(pop_menubar, this);
					}
					break;
				default:
					break;
			}
		}
		return true;
	}
	
	/**
	 *	自定义popup的click监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 全文搜索
		case R.id.btn_search:
			startActivityForResult(new Intent(BookContentActivity.this, BookSearchWordActivity.class), Constants.REQUEST_CODE_ACTIVITY);
			break;
		// 加大字体
		case R.id.btnFontSizeBigger:
			if(bookFactory.changeTextSize(Constants.FONT_SIZE_BIGGER)){
				refreshCurPage();
			}
			break;
		// 减小字体
		case R.id.btnFontSizeSmaller:
			if(bookFactory.changeTextSize(Constants.FONT_SIZE_SMALLER)){
				refreshCurPage();
			}
			break;
		// 打开目录
		case R.id.btnCategory:
			startActivityForResult(new Intent(BookContentActivity.this, BookCategoryActivity.class), Constants.REQUEST_CODE_ACTIVITY);
			break;
		// 打开语音
		case R.id.btnTTS:
			if(isSpeaking){
				isSpeaking = false;
				speekUtil.pauseSpeaking();
			}else{
				isSpeaking = true;
				speekUtil.startSpeaking();
			}
			changeBtnDrawableTTS();
			break;
		default:
			break;
		}
	}
	
	/**
	 * 关闭弹出菜单
	 */
	public void dismissMenuPop(){
		menuPopup.dismiss();
//		AnimationUtil.hideMenuBarAnimate(pop_menubar, this, menuPopup);
	}
	
	/**
	 * 改变播放按钮的背景图，正在朗读则显示暂停，否则显示播放
	 */
	public void changeBtnDrawableTTS(){
		if(isSpeaking){
			btnTTS.setCompoundDrawablesWithIntrinsicBounds(null, drawablePause, null, null);
		}else{
			btnTTS.setCompoundDrawablesWithIntrinsicBounds(null, drawablePlay, null, null);
		}
	}
	
	/**
	 * 接收其他activity传递过来的参数
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 关闭菜单popup
		dismissMenuPop();
		
		if(requestCode == Constants.REQUEST_CODE_ACTIVITY){
			switch (resultCode) {
			// 从目录列表跳转过来
			case Constants.RESULT_CODE_CATEGORY:
				
				// 获取点击的目录下标
				int position = data.getExtras().getInt(Constants.RESULT_KEY_CATEGORY);
				int mbbIndex = bookFactory.getCategories().get(position).getPosition();
				
				// 保存当前目录对应文字的下标
				editor = preference.edit();
				editor.putInt(currentBook.getPath() + Constants.PREFERENCE_KEY_MBBINDEX, mbbIndex);
				editor.commit();
				
				// 刷新当前页面
				refreshCurPage();
				
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 传递消息，刷新小说当前页面UI
	 */
	@SuppressLint("HandlerLeak") 
	private Handler mHandler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            super.handleMessage(msg);  
            switch (msg.what) {  
            case 0:  
            	mBookContentView.invalidate();
                break;
            case 1:
            	bookFactory.drawPercent(msg.getData().getFloat("p") + "%", mCurCanvas);
            	mBookContentView.invalidate();
            	break;
            default:  
                break;  
            }  
        }  
    };  
	
    /**
     * 向前翻一页
     */
    public void doPagePre(){
    	bookFactory.pagePre();
		bookFactory.doDraw(mCurCanvas);
		refreshSpeaking();
		mHandler.sendEmptyMessage(0);
    }
    
    /**
     * 向后翻一页
     */
    public void doPageNext(){
    	bookFactory.pageNext();
		bookFactory.doDraw(mCurCanvas);
		refreshSpeaking();
		mHandler.sendEmptyMessage(0);
    }
    
    /**
     * 改变配置后刷新当前页面
     */
    public void refreshCurPage(){
    	bookFactory.initFactory();
		bookFactory.pageNext();
		bookFactory.doDraw(mCurCanvas);
		refreshSpeaking();
		mHandler.sendEmptyMessage(0);
    }
    
    /**
     * 刷新朗读
     */
    public void refreshSpeaking(){
    	speekUtil.resetIndex();
		if(isSpeaking){
			speekUtil.startSpeaking();
		}
    }
    
    /**
     * 弹出toast
     */
    public void showTip(final String str) {
		mToast.setText(str);
		mToast.show();
	}
    
    /**
     * 弹出toast
     */
    public void showTip(final int resId) {
    	mToast.setText(resId);
    	mToast.show();
    }
    
}
